<template>
	<view class=" full-screen">
		<view
			style="z-index:0;position:absolute;left:0;right:0;top:0;bottom:0;background-image:radial-gradient(circle at left top, #D8230A26 50%, transparent 50%);background-size:396px 396px;background-repeat:no-repeat;filter:blur(50px);">
		</view>
		<uni-nav-bar ref="navBar" fixed statusBar :border="false" backgroundColor="transparent" @clickLeft="goBack">
			<!-- <template v-slot:left>
				<image class="size-32" src="@/static/svg/icon-back.svg"  v-if="!redirect" />
			</template> -->
		</uni-nav-bar>
		<view class="flex-col item-center relative" :style="`height: calc(100vh - ${navBarHeight || 0}px);z-index:1;`">
			<image style="width:88px;height:88px;margin-top:52px;" src="@/static/image/login-logo.png" />
			<text class="mt-20 text-center text-color-regular fs-20 font-semibold">欢迎来到火动通告</text>
			<view class="w-full flex-1 h-0" style="max-height:190px;"></view>
			<view class="mx-16 black text-center fs-14 font-normal">
				<view class="flex align-center font-s14" @click="agreementCheckHandle">
					<label for="agreement" class="flex align-center">
						<image v-if="isAgreementCheck" class="size-13" src="@/static/svg/radio-checked.svg"></image>
						<image v-else class="size-13" src="@/static/svg/radio-default.svg"></image>
						我已阅读并同意<text class="color-primary" @click.stop="toLink('user')">《用户服务协议》</text>和<text class="color-primary" @click.stop="toLink('privacy')">《隐私协议》</text>
					</label>
				</view>
				<button class="mt-17 h-46 leading-46 radius-23 bg-primary text-white fs-16 font-semibold"
					:open-type="isAgreementCheck && !token ? 'getPhoneNumber' : ''" @getphonenumber="getPhoneNumber"
					@click="quickLoginHandle">手机号快捷登录/注册</button>
				<!-- <button class="my-20 mx-0 h-38 leading-38 radius-20 uni-border text-color-hint fs-14 font-normal" @click="noLoginHandle" v-if="!redirect">暂不登录</button> -->
			</view>
		</view>

		<NickNameAndAvatarPopup ref="popup" @onSubmit="onSubmit" />
	</view>
</template>

<script setup name="Login">
	import {
		computed,
		onMounted,
		ref,
		watch
	} from 'vue'
	import {
		authCodeApi,
		getWxMobileApi
	} from '@/api/auth.js'
	import {
		uploadFileApi
	} from '@/api/common.js'
	import NickNameAndAvatarPopup from './components/NickNameAndAvatarPopup.vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '@/stores/modules/user.js'
	import {
		getEnterInfo,
		preApplyMerchant
	} from '@/api/businessEnterApply.js'
	import { useWebView } from '@/hooks/useWebView.js'
	
	const webview = useWebView()
	let redirect = ref(null)
	let code = ref(null)
	const userStore = useUserStore()
	const show = ref(false)
	const navBar = ref(null)
	const toLink = (type) => {
		if (type === 'user') {
			webview.showUserAgreement('用户服务协议')
		} else if (type === 'privacy') {
			webview.showPrivacyPolicy('隐私协议')
		}
	}
	// // 查看用户协议
	// const showUserAgreement = (title = '用户协议') => {
	// 	uni.navigateTo({
	// 		url: `/pagesC/webview/webview?url=${encodeURIComponent(UserAgreementURL)}&title=${encodeURIComponent(title)}`
	// 	})
	// }
	
	// // 查看隐私政策
	// const showPrivacyPolicy = (title = '隐私政策') => {
	// 	uni.navigateTo({
	// 		url: `/pagesC/webview/webview?url=${encodeURIComponent(PrivacyPolicyURL)}&title=${encodeURIComponent(title)}`
	// 	})
	// }
	const goBack = () => {
		if (!redirect.value) {
			// 仅有一个页面时，返回首页
			if (getCurrentPages().length === 1) {
				uni.reLaunch({
					url: '/homePages/pages/home/home'
				})
				return
			}
			uni.navigateBack()
		}
	}

	const isAgreementCheck = ref(false)

	const agreementCheckHandle = () => {
		isAgreementCheck.value = !isAgreementCheck.value
	}

	const popup = ref(null)
	const openId = ref('')
	const token = ref('')
	const linkPages = (result) => {
		const token = uni.getStorageSync('token')
		if (token) {
			uni.redirectTo({
				url: '/homePages/pages/home/home'
			})
			return
		}
		// if(userStore.$state.userInfo.merchantInfo){
		if (result && result.merchantState) {
			uni.redirectTo({
				url: '/pages/login/login'
			})
			return
		}

		if (redirect.value == 'busi' && code.value) {
			let params = code.value ? `?code=${code.value}` : ``
			uni.redirectTo({
				url: `/applyPages/bussinessApply/bussinessAgreement${params}`
			})
		} 
		// else {
		// 	uni.redirectTo({
		// 		url: '/pages/login/login'
		// 	})
		// }
	}
	const getMerInfo = async (stateResult) => {
		let result = await getEnterInfo({
			openid: openId.value
		})
		userStore.setMerchantInfo(result)
		return
		// result = null
		// 链接进入
		if(stateResult){
			if(stateResult.state == 0){
				linkPages(result)
			}else {
				const token = uni.getStorageSync('token')
				if (token) {
					uni.redirectTo({
						url: '/homePages/pages/home/home'
					})
				}
			}
			return
		}
		// 非链接逻辑
		if (result) {
			userStore.setMerchantInfo(result)
			
			if (result.auditState == 1 || result.auditState == 3 || result.auditState == 4) {
				uni.redirectTo({
					url: '/applyPages/bussinessApply/applyResult/applyResult'
				})
			} else {
				linkPages(result)
			}
		} else {
			linkPages()
		}
	}
	const getPhoneNumber = async ({
		detail
	}) => {
		if (detail.errMsg === 'getPhoneNumber:ok') {
			const result = await getWxMobileApi({
				encryptedData: detail.encryptedData,
				iv: detail.iv,
				openId: openId.value
			})
			if (result) {
				uni.setStorageSync('wxPhone', result)
				if(code.value){
					let params = code.value ? `?code=${code.value}` : ``
					uni.redirectTo({
						url: `/applyPages/bussinessApply/bussinessAgreement${params}`
					})
				}
				
				// if(code.value){
				// 	getPreApply()
				// }else{
				// 	getMerInfo()
				// }
			}
		}
	}


	const quickLoginHandle = async (e) => {
		if (!isAgreementCheck.value) {
			uni.showToast({
				icon: 'none',
				title: '请先阅读并同意用户协议与隐私政策'
			})
		}
	}

	// 不登录，返回上一页面
	const noLoginHandle = () => {
		// 仅有一个页面时，返回首页
		if (getCurrentPages().length === 1) {
			uni.reLaunch({
				url: '/homePages/pages/home/home'
			})
		} else {
			uni.navigateBack()
		}
	}
		// 有链接
	const getPreApply = async () => {
		let result = await  preApplyMerchant({openid:openId.value,settleCode:code.value})
		const token = uni.getStorageSync('token')
		const wxPhone = uni.getStorageSync('wxPhone')
		if(result){
			// 该链接已经审核，看状态
			if(result.state ==1 || result.state ==2){
				uni.redirectTo({
					url: '/applyPages/bussinessApply/applyResult/applyResult'
				})
			}else if(result.state == 4){
				if (token) {
					uni.reLaunch({
						url: '/homePages/pages/home/home'
					})
				}else if (redirect.value == 'busi' && code.value && wxPhone) {
					let params = code.value ? `?code=${code.value}` : ``
					uni.redirectTo({
						url: `/applyPages/bussinessApply/bussinessAgreement${params}`
					})
				} 
			} else{
				// result.state = 0
				if(result.state == 3){
					// 已经入驻成功
					code.value = ''
					userStore.setInestCode(null)
					if (token) {
						uni.reLaunch({
							url: '/homePages/pages/home/home'
						})
					}else{
						uni.reLaunch({
							url: '/pages/login/login'
						})
					}	
				}
				// if(result.state == 0)
				getMerInfo(result)
			}
		}
	}

	const getOpenId = async () => {
		const res = await uni.login({
			provider: 'weixin'
		})
		if (res.code) {
			const result = await authCodeApi((res.code))
			if (result.openId) {
				// 已注册，直接跳转到首页
				// token.value = result.token
				// userStore.setToken(result.token)
				openId.value = result.openId
				uni.setStorageSync('openId', result.openId)
				// getPreApply()
			} else {
				// 未注册
				// openId.value = result.openId

			}
			// if(redirect.value == 'bussinessAgreement'){
			// 	let params = code.value?`?code=${code.value}`:``
			// 	uni.redirectTo({
			// 		url: `/applyPages/bussinessApply/bussinessAgreement${params}`
			// 	})
			// }
		}
	}

	const onSubmit = async (form) => {
		popup.value.showPopup(false)
		uni.showLoading()
		await userStore.login({
			openId: openId.value,
			...form
		})
		await userStore.getUserInfo()
		uni.hideLoading()
		if (redirect.value == 'busi') {
			let params = code.value ? `?code=${code.value}` : ``
			uni.redirectTo({
				url: `/applyPages/bussinessApply/bussinessAgreement${params}`
			})
		} else {
			uni.redirectTo({
				url: '/homePages/pages/home/home'
			})
		}
	}
	
	const navBarHeight = computed(() => {
		const statusBarHeight = uni.getWindowInfo().statusBarHeight
		const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
		return navigationBarHeight
	})
	
	onMounted(() => {
		const token = uni.getStorageSync('token')
		const wxPhone = uni.getStorageSync('wxPhone')
		const stoOpenId = uni.getStorageSync('openId')
		openId.value = stoOpenId
		// 1.登录状态下，点击邀请链接=》判断是否已入驻
			//待审核：审核状态下跳转状态界面
			// 已入驻：进入界面
			// 未入驻：首页弹窗邀请入驻
		// 2.未登录状态下：
			// 判断是有已经加入其他商家或者已经是商户 =》是：登录界面弹窗
			// 否：跳转申请界面
			
		if (token) {
			return
			uni.reLaunch({
				url: '/homePages/pages/home/home'
			})
			// if(code.value){
			// 	// 邀请码判断是否入驻过
			// 	getPreApply()
			// }else{
			// 	// 获取商家入驻信息
			// 	getMerInfo()
			// }
		} else {
			// if (wxPhone && stoOpenId) {
			// 	if(code.value){
			// 		// 邀请码判断是否入驻过
			// 		getPreApply()
			// 	}else{
			// 		// 获取商家入驻信息
			// 		getMerInfo()
			// 	}
			// 	// getMerInfo()
			// 	// linkPages()
			// } else {
			// 	show.value = true
			// 	getOpenId()
			// }
		}

	})
	onLoad((query) => {
		// code.value = 'XFKUG7'
		// userStore.setInestCode('XFKUG7')
		// redirect.value = 'bussinessAgreement'
		if (query.code) {
			redirect.value = query.re
			code.value = query.code
			if (query.code) {
				userStore.setInestCode(query.code)
				getOpenId()
			}
		}
	})
</script>
<style scoped lang="scss">
	.font-s14{
		font-size: 28rpx;
	}
</style>